var $table = $('#table');
var URI_LIST = "/sec/permission/list";
var URI_CREATE = "/sec/permission/create";
var URI_UPDATE = "/sec/permission/update/";
var URI_DEL = "/sec/permission/delete/";
var createFrom = "#SecPermissioncreateForm";
var updateForm = "#SecPermissionupdateForm";
var idField = "permissionId";
var createValidation = null;
var updateValidation = null;
var fieldCloumns = [[
    {field: 'name', title: '权限名称',width:200},
    {field: 'permissionId', title: '编号',width:200},
    {field: 'systemId', title: '系统',width:200},
    {field: 'category', title: '权限类别', formatter: categoryFormatter,width:100},
    {field: 'value', title: '权限值',width:100},
    {field: 'uri', title: '资源路径',width:400},
    {field: 'icon', title: '资源图标', formatter: iconFormatter,width:100},
    {field: 'orders', title: '资源顺序',width:100},
    {field: 'other', title: '其他授权资源',width:400}
]]
easyloader.base = "/plugins/easyui/"; // 设置 easyui 的基本目录
easyloader.theme = "bootstrap";
easyloader.load('treegrid', function () { // 加载指定的模块
    $table.treegrid({
        url: URI_LIST,
        idField: 'permissionId',
        method: "get",
        treeField: 'name',
        parentField: "pid",
        fitColumns: true,
        columns: fieldCloumns,
        onBeforeExpand: function (node, param) {
            $table.treegrid('options').url = URI_LIST + "?pid=" + node.permissionId;
        },
        loadFilter: function (dd, parent) {
            var data = dd.rows;
            for (var i = 0; i < data.length; i++) {
                if (data[i].category == "1" || data[i].category == "2") {
                    data[i].children = [];
                    data[i].state = "closed";
                }
            }
            return data;
        }
    });
});

function initValidate(formId) {
    var validator = $(formId).validate({
        rules: {
            systemId: {required: true, digits: true},
            name: {required: true, maxlength: 100},
            category: {required: true, maxlength: 4},
            value: {required: true, maxlength: 200},
            uri: {required: true, maxlength: 400},
            icon: {required: true, maxlength: 100},
            state: {required: true, maxlength: 2},
            pid: {required: true, digits: true},
            orders: {required: true, digits: true},
            other: {required: true, maxlength: 500}
        }
    });
    return validator;
}

function iconFormatter(value, row, index) {
    return "<i class='" + value + "'></i>"
}

function categoryFormatter(value, row, index) {
    if (value == "1") {
        return "模块";
    }
    if (value == "2") {
        return "页面";
    }
    if (value == "3") {
        return "权限";
    }
    return "-";
}

// 新增
var createDialog;

function createAction() {
    var row = $table.treegrid("getSelected");
    if (row != null && row.category == "3") {
        $.confirm({
            theme: 'dark',
            animation: 'rotateX',
            closeAnimation: 'rotateX',
            title: false,
            content: "已经是最小级别了,不允许添加子集",
            buttons: {
                confirm: {
                    text: '确认',
                    btnClass: 'waves-effect waves-button waves-light'
                }
            }
        });
        return;
    }
    loadDialog("#showModal", "新增", URI_CREATE + ".html", function () {
        initMaterialInput();
        createValidation = initValidate(createFrom);
        if(row !=null){
            $("#pid").val(row.permissionId);
        }
        $(createFrom).ajaxForm({
            target: '#btn-SecPermission-submit',   // target element(s) to be updated with server response
            dataType: 'json',
            url: URI_CREATE,
            beforeSubmit: function (formData, jqForm, options) {
                return createValidation.valid();
            },
            success: function (result, statusText, xhr, $form) {
                if (result.code != "0000") {
                    showMessage(result.code || result.desc, "error");
                } else {
                    $("#showModal").modal("hide");
                    showMessage("新增资源成功!");
                    if (row != null) {
                        $table.treegrid("reload", row.permissionId)
                    } else {
                        $table.treegrid("reload")
                    }
                }
            }
        });
    })
    $(createFrom + " .form-need-hide").hide();
}

// 编辑
var updateDialog;

function updateAction() {
    var rows = $table.treegrid('getSelections');
    if (rows.length != 1) {
        $.confirm({
            title: false,
            content: '请选择一条记录！',
            autoClose: 'cancel|3000',
            backgroundDismiss: true,
            buttons: {
                cancel: {
                    text: '取消',
                    btnClass: 'waves-effect waves-button'
                }
            }
        });
    } else {
        updateDialog = $.dialog({
            animationSpeed: 300,
            title: '编辑',
            columnClass: 'col-md-10',
            content: 'url:' + URI_UPDATE + rows[0].permissionId + ".html",
            onContentReady: function () {
                initMaterialInput();
                updateValidation = initValidate(updateForm)
                $(updateForm).ajaxForm({
                    target: '#btn-SecPermission-update',   // target element(s) to be updated with server response
                    dataType: 'json',
                    url: URI_UPDATE + rows[0].permissionId,
                    beforeSubmit: function (formData, jqForm, options) {
                        return updateValidation.valid();
                    },
                    success: function (result, statusText, xhr, $form) {
                        if (result.code != "0000") {
                            $.confirm({
                                theme: 'dark',
                                animation: 'rotateX',
                                closeAnimation: 'rotateX',
                                title: false,
                                content: result.data.errorMsg || result.desc,
                                buttons: {
                                    confirm: {
                                        text: '确认',
                                        btnClass: 'waves-effect waves-button waves-light'
                                    }
                                }
                            });
                        } else {
                            updateDialog.close();
                            $table.bootstrapTable('refresh');
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $.confirm({
                            theme: 'dark',
                            animation: 'rotateX',
                            closeAnimation: 'rotateX',
                            title: false,
                            content: textStatus,
                            buttons: {
                                confirm: {
                                    text: '确认',
                                    btnClass: 'waves-effect waves-button waves-light'
                                }
                            }
                        });
                    }
                });
            }
        });
    }
}

// 删除
var deleteDialog;

function deleteAction() {
    var rows = $table.treegrid('getSelections');
    if (rows.length == 0) {
        $.confirm({
            title: false,
            content: '请至少选择一条记录！',
            autoClose: 'cancel|3000',
            backgroundDismiss: true,
            buttons: {
                cancel: {
                    text: '取消',
                    btnClass: 'waves-effect waves-button'
                }
            }
        });
    } else {
        deleteDialog = $.confirm({
            type: 'red',
            animationSpeed: 300,
            title: false,
            content: '确认删除该记录吗？',
            buttons: {
                confirm: {
                    text: '确认',
                    btnClass: 'waves-effect waves-button',
                    action: function () {
                        var ids = new Array();
                        for (var i in rows) {
                            ids.push(rows[i].permissionId);
                        }
                        $.ajax({
                            type: 'get',
                            url: URI_DEL + ids.join("-"),
                            success: function (result) {
                                if (result.code != "0000") {
                                    $.confirm({
                                        theme: 'dark',
                                        animation: 'rotateX',
                                        closeAnimation: 'rotateX',
                                        title: false,
                                        content: result.desc,
                                        buttons: {
                                            confirm: {
                                                text: '确认',
                                                btnClass: 'waves-effect waves-button waves-light'
                                            }
                                        }
                                    });
                                } else {
                                    deleteDialog.close();
                                    for (var i in rows) {
                                        $table.treegrid("remove", rows[i].permissionId)
                                    }

                                }
                            },
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                                $.confirm({
                                    theme: 'dark',
                                    animation: 'rotateX',
                                    closeAnimation: 'rotateX',
                                    title: false,
                                    content: textStatus,
                                    buttons: {
                                        confirm: {
                                            text: '确认',
                                            btnClass: 'waves-effect waves-button waves-light'
                                        }
                                    }
                                });
                            }
                        });
                    }
                },
                cancel: {
                    text: '取消',
                    btnClass: 'waves-effect waves-button'
                }
            }
        });
    }
}

function loadDialog(selectEL, title, loadURI, success) {
    $(selectEL).find(".modal-title").html(title);
    $(selectEL).find('.modal-body').load(loadURI, function (response, status, xhr) {
        $('.selectpicker').selectpicker({
            noneSelectedText: "--请选择--",
            selectOnTab: true,
            liveSearch: true
        });
        $(selectEL).modal("show");
        if (success) {
            success();
        }
    });
}